package com.example.children.controller;


import com.example.children.Exception.LoginException;
import com.example.children.Util.JwtUtil;
import com.example.children.Util.Tools;
import com.example.children.Util.tool;
import com.example.children.Model.ResponseModel;
import io.jsonwebtoken.Claims;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;

import static com.example.children.Util.JwtUtil.parseJwt;

@RestController
@CrossOrigin(origins = {"http://localhost:8080","http://localhost:63342"}) // 允许该源
//@CrossOrigin(origins = "http://localhost:63342") // 允许该源
@RequestMapping("/GetToken")  //类名
public class GetToken {   //更新Token



    @PostMapping("/refreshToken") //方法名
    public ResponseModel<Map<String, String>> login(@RequestBody String refreshToken){
        System.out.println("进入refreshToken方法：" );
        Map<String, String> toKenMap =new HashMap();
        Integer code= Tools.Success;
        String msg= tool.success;
        try {
            // 验证 refreshToken 是否有效
            Claims claims = parseJwt(refreshToken);
            // 如果 refreshToken 有效，生成新的 accessToken
            String userId = claims.getSubject();  // 获取用户 ID
            System.out.println("用户id："+userId);
            String newAccessToken = JwtUtil.generateToken(userId,1000*10, (String) claims.get("role"));
            String newRefreshToken= JwtUtil.generateToken(userId,1000*60, (String) claims.get("role"));
            toKenMap.put("accessToken",newAccessToken);
            toKenMap.put("refreshToken",newRefreshToken);
            return new ResponseModel<>(code,msg,toKenMap);//响应给前端的对象
        } catch (Exception e) {
            System.out.println("refreshToken No");
            throw new LoginException("refreshToken无效，已经过期，需要重新登录！！");
        }
    }



}
